'use client';

import { useState, useEffect, useRef } from 'react';

interface Props {
  showLeaderboard: boolean;
  onToggleView: (showLeaderboard: boolean) => void;
  children: React.ReactNode;
}

export default function Sidebar({ showLeaderboard, onToggleView, children }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const sidebarRef = useRef<HTMLDivElement>(null);

  // 检测屏幕尺寸
  useEffect(() => {
    const checkScreenSize = () => {
      const mobile = window.innerWidth < 1024;
      setIsMobile(mobile);
      // 桌面端默认展开，移动端默认收起
      setIsOpen(!mobile);
    };
    
    checkScreenSize();
    window.addEventListener('resize', checkScreenSize);
    return () => window.removeEventListener('resize', checkScreenSize);
  }, []);

  // 点击外部关闭（仅移动端）
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (isMobile && isOpen && sidebarRef.current && !sidebarRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen, isMobile]);

  const toggleSidebar = () => {
    setIsOpen(!isOpen);
  };

  return (
    <>
      {/* 移动端遮罩层 */}
      {isOpen && isMobile && (
        <div 
          className="fixed inset-0 bg-black/50 backdrop-blur-sm z-40 lg:hidden transition-opacity duration-300"
          onClick={() => setIsOpen(false)}
        />
      )}

      {/* 侧边栏 */}
      <div
        ref={sidebarRef}
        className={`
          fixed lg:relative top-0 left-0 h-screen lg:h-[calc(100vh-73px)]
          w-52 bg-card border-r border-border
          z-50 lg:z-auto
          transform transition-transform duration-300 ease-in-out
          ${isOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'}
          shadow-xl lg:shadow-none
          flex-shrink-0
        `}
      >
        <div className="h-full flex flex-col">
          {/* 头部 */}
          <div className="p-3 border-b border-border flex items-center justify-between">
            <h2 className="text-base font-semibold text-foreground">导航</h2>
            {/* 移动端关闭按钮 */}
            <button
              onClick={toggleSidebar}
              className="lg:hidden w-8 h-8 rounded-lg hover:bg-accent transition-colors flex items-center justify-center"
            >
              <svg className="w-5 h-5 text-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* 切换按钮 - 竖向排列 */}
          <div className="p-3 border-b border-border">
            <div className="flex flex-col gap-1.5 bg-card/50 p-1 rounded-lg border border-border/50">
              <button
                onClick={() => onToggleView(false)}
                className={`w-full px-3 py-2 rounded-md transition-all duration-300 text-sm font-medium ${
                  !showLeaderboard
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-accent/50'
                }`}
              >
                挑战
              </button>
              <button
                onClick={() => onToggleView(true)}
                className={`w-full px-3 py-2 rounded-md transition-all duration-300 text-sm font-medium ${
                  showLeaderboard
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-accent/50'
                }`}
              >
                排行榜
              </button>
            </div>
          </div>

          {/* 内容区域 */}
          <div className="flex-1 overflow-y-auto p-3">
            {children}
          </div>
        </div>
      </div>

      {/* 移动端展开按钮 */}
      <button
        onClick={toggleSidebar}
        className="lg:hidden fixed bottom-6 left-6 w-14 h-14 rounded-full bg-primary text-primary-foreground shadow-lg hover:shadow-xl transition-all duration-300 z-40 flex items-center justify-center"
      >
        <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
        </svg>
      </button>
    </>
  );
}

